package com.demo.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import com.demo.dao.UserDao;
import com.demo.entity.User;

public class JDBCUserDaoImpl implements UserDao {

	private static Connection connection = null;
	
	private Connection getConnection() {
		String url = "jdbc:mysql://localhost:3306/test";
		String username = "admin";
		String password = "admin";
		try {
			if(connection==null){
				Class.forName("com.mysql.jdbc.Driver");
				connection = DriverManager.getConnection(url, username,
						password);
			}
		} catch (Exception e) {
			System.out.println("数据库连接失败！");
			e.printStackTrace();
		}
		return connection;
	}
	
	@Override
	public int insertUser(User user) {
		int n = 0;
		try {
			String sql = "insert into user(userid, username, age) values(?,?,?)";
			PreparedStatement pst =  getConnection().prepareStatement(sql);
			pst.setString(1, user.getUserId());
			pst.setString(2, user.getUserName());
			pst.setInt(3, user.getAge());
			n = pst.executeUpdate();
			pst.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return n;
	}

	@Override
	public int insertUsers(List<User> users) {
		int n = 0;
		if(users==null) return n;
		for(User u:users){
			n +=insertUser(u);
		}
		return n;
	}

	@Override
	public int updateUser(User user) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int delete(User user) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public List<User> selectUsers(User user) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public User selectUser(User user) {
		// TODO Auto-generated method stub
		return null;
	}

}
